<script setup>
import { nextTick, onMounted, onUnmounted, reactive, ref, watch } from 'vue'
import { useShowLoginDialogStore } from '@/store/showLoginDiaolg'
import { useShowRegisterDialogStore } from '@/store/showRegisterDiaolg'
import { useTokenStore } from '@/store/token'
import { useUserInfoStore } from '@/store/userInfo'
import { userLoginService, userLoginImageCheckCodeService } from '@/api/user'

import verify from '@/utils/verify.js' // 导入正则校验工具类
import { getCurrentInstance } from "vue"

const loading = ref(false)

// 获取全局注册的组件
const { proxy } = getCurrentInstance();

// 登录框状态
const showLoginDialogStore = useShowLoginDialogStore();
// token状态
const tokenStore = useTokenStore();
// 用户信息状态
const userInfoStore = useUserInfoStore();

// 显示用户注册弹框
const showRegisterDialogStore = useShowRegisterDialogStore()
const showRegisterDialog = () => {
  // 先关闭登录框
  showLoginDialogStore.setShowLoginDialog(false)
  // 再显示注册框
  showRegisterDialogStore.setShowRegisterDialog(true)
}

// 处理关闭用户登录框逻辑
const handleLoginDialogClose = () => {
  showLoginDialogStore.setShowLoginDialog(false)
}

// 获取图片验证码
const imageCheckCodeUrl = ref()
const getImageCheckCode = async () => {
  // axios({
  //   url: '/api/user/user/getLoginImageCheckCode',
  //   method: 'get',
  //   responseType: 'blob' //选择接收方式为blob
  // }).then((res) => {
  //   // console.log("res", res)
  //   imageCheckCodeUrl.value = URL.createObjectURL(res.data)
  // }).catch((err) => {
  //   // console.log("err", err)
  // })

  loading.value = true
  let res = await userLoginImageCheckCodeService()
  imageCheckCodeUrl.value = URL.createObjectURL(res.data)
  loading.value = false
}

// 用户登录表单
const formDataRef = ref()
const formData = ref({
  password: 'ld123456',
  email: '1136749840@qq.com',
  imageCheckCode: 'vcgdq',
})
const rules = {
  email: [
    { required: true, message: "请输入邮箱", trigger: 'blur' },
    { max: 150, message: "邮箱太长", trigger: 'blur' },
    { validator: verify.email, message: "请输入正确的邮箱", trigger: 'blur' }
  ],
  password: [
    { required: true, message: "请输入密码", trigger: 'blur' },
    { min: 6, message: "密码只能是字母、数字,长度为6-20位", trigger: 'blur' },
    { max: 20, message: "密码只能是字母、数字,长度为6-20位", trigger: 'blur' },
    { validator: verify.password, message: "密码只能是字母、数字,长度为6-20位", trigger: 'blur' },
  ],
  imageCheckCode: [{ required: true, message: "请输入图形验证码", trigger: 'blur' }],
}

// 显示登录框，禁止页面滚动，隐藏滚动条
const stopSrcoll = () => {
  console.log("Login页面 禁止页面滑动")
  let mo = function (e) { e.preventDefault(); };
  document.body.style.overflow = 'hidden';
  document.addEventListener("touchmove", mo, false); // 禁止页面滑动
}

// 关闭登录框，允许页面滚动，显示滚动条
const openSrcoll = () => {
  console.log("Login页面 出现滚动条")
  let mo = function (e) { e.preventDefault(); };
  document.body.style.overflow = ''; // 出现滚动条
  document.removeEventListener("touchmove", mo, false);
}

// 用户登录
const login = async () => {
  await formDataRef.value.validate(async (valid) => {
    if (!valid) {
      console.log("校验未通过")
      getImageCheckCode() // 重新获取图片验证码
      return
    }
    console.log("校验通过，可以进行用户登录")
    let result = await userLoginService(formData.value)

    // 使用我们自己封装的Notification组件
    // proxy.Notification.success("用户：" + result.data.nickname + ' 登录成功!')

    // 将得到的token存储到pinia中
    tokenStore.setToken(result.data.token)

    // 将得到的用户信息存储到pinia中
    userInfoStore.userInfo.userId = result.data.userId
    userInfoStore.userInfo.nickname = result.data.nickname
    userInfoStore.userInfo.avatar = result.data.avatar

    // 重置表单
    formDataRef.value.resetFields()

    // 关闭登录框
    showLoginDialogStore.setShowLoginDialog(false)

    // 登陆后 刷新页面
    window.location.reload()
  })
}

onMounted(() => {
  // 获取图片验证码
  getImageCheckCode()
  // 禁止body滚动条
  stopSrcoll()
})

onUnmounted(() => {
  // 开启body滚动条
  openSrcoll()
})
</script>

<template>
  <!-- 用户登录 -->
  <div class="login-panel">
    <!-- 点击空白处不关闭 -->
    <el-dialog v-model="showLoginDialogStore.showLoginDialog" :close-on-click-modal="false"
      :close-on-press-escape="false" :before-close="handleLoginDialogClose" @open="stopSrcoll()" @close="openSrcoll()">
      <div class="panel-title">云舟 - 登录</div>
      <div class="login-form">
        <!-- 表单 -->
        <el-form :model="formData" :rules="rules" ref="formDataRef" class="login-form">
          <!-- 邮箱 -->
          <el-form-item prop="email">
            <el-input size="large" clearable placeholder="请输入邮箱" v-model="formData.email">
              <template #prefix>
                <span class="iconfont icon-email"></span>
              </template>
            </el-input>
          </el-form-item>
          <!-- 用户密码 -->
          <el-form-item prop="password">
            <el-input size="large" clearable show-password placeholder="请输入密码" v-model="formData.password">
              <template #prefix>
                <span class="iconfont icon-password"></span>
              </template>
            </el-input>
          </el-form-item>
          <!-- 登录 图形验证码 -->
          <el-form-item prop="imageCheckCode">
            <div class="image-check-code-panel">
              <el-input size="large" clearable placeholder="请输入图形验证码" v-model="formData.imageCheckCode">
                <template #prefix>
                  <span class="iconfont icon-check_code"></span>
                </template>
              </el-input>
              <img v-loading="loading" :src="imageCheckCodeUrl" class="image-check-code" @click="getImageCheckCode">
            </div>
          </el-form-item>
          <!-- 记住我、忘记密码、账号区 -->
          <!-- 注册、密码重置用 -->
          <el-form-item>
            <div class="no-account">
              <a href="#" @click="showUserResetPasswordDialog()">忘记密码？</a>
              <a href="#" @click="showRegisterDialog()">没有账号？</a>
            </div>
          </el-form-item>
          <!-- 按钮区 -->
          <el-form-item>
            <!-- 这里因为是原生的button，需阻止默认行为，再进行我们自己的校验逻辑 -->
            <button class="op-btn" @click.prevent="login()" type="button">登录</button>
          </el-form-item>
        </el-form>
      </div>
    </el-dialog>
  </div>
</template>

<style>
.el-dialog__header {
  padding: 0px;
}

/* 修改登录框原css */
.el-dialog {
  width: 400px;
  border-radius: 5px;
}

/* 用户登录 */
.login-panel .panel-title {
  font-size: 20px;
  padding: 0px 10px 20px;
  color: #252933;
  border-bottom: 1px solid rgba(200, 202, 207, 0.5);
}

/* 登录表单 */
.login-panel .login-form {
  padding: 10px 5px 0px;
}

/* 图形验证码区 */
.login-panel .login-form .image-check-code-panel {
  width: 100%;
  display: flex;
  justify-content: space-between;
}

.login-panel .login-form .image-check-code-panel .image-check-code {
  width: 130px;
  height: 42px;
  margin-left: 10px;
  cursor: pointer;
}

/* 记住我区域 */
.login-panel .login-form .rememberme-panel {
  width: 100%;
}

/* 忘记密码、账号区域 */
.login-panel .login-form .no-account {
  width: 100%;
  display: flex;
  justify-content: space-between;
}

.login-panel .login-form .no-account a {
  border-bottom: 1px solid #fff;
}

.login-panel .login-form .no-account a:hover {
  border-bottom: 1px solid #000;
}

/* 按钮区 */
.login-panel .login-form .op-btn {
  width: 100%;
  height: 40px;
  cursor: pointer;
  border-radius: 4px;
  color: #fff;
  background-color: #67C23A;
  font-size: 16px;
  border: 0px;
}
</style>